package com.example.backspring.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/upload")
@Tag(name = "上传文件", description = "用来上传需要部署的jar包或者前端的代码")
@Slf4j
public class UploadFileController {

    // 文件保存目录
    private static final String UPLOAD_DIR = "D:\\AppData\\file\\";

    @PostMapping
    @Operation(summary = "上传文件", description = "将文件保存到服务器D:\\AppData目录")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();

        // 检查文件是否为空
        if (file.isEmpty()) {
            response.put("success", false);
            response.put("message", "请选择要上传的文件");
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        try {
            // 创建保存目录（如果不存在）
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
                log.info("创建上传目录: {}", UPLOAD_DIR);
            }

            // 获取文件名并构建保存路径
            String fileName = file.getOriginalFilename();
            String filePath = UPLOAD_DIR + fileName;
            File destFile = new File(filePath);

            // 保存文件
            file.transferTo(destFile);
            log.info("文件上传成功: {}", filePath);

            // 构建成功响应
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("data", Map.of(
                    "id", System.currentTimeMillis(), // 简单使用时间戳作为ID
                    "name", fileName,
                    "size", file.getSize(),
                    "url", "/uploads/" + fileName
            ));

            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}